//
//  VOLmyMesgViewController.m
//  Volver
//
//  Created by administrator on 14-10-28.
//  Copyright (c) 2014年 vol. All rights reserved.
//

#import "VOLmyMesgViewController.h"
#import "REFrostedViewController.h"
#import "common.h"
#import "VOLAppDelegate.h"
#import "VOLChatViewController.h"
#import "VOLChatUser.h"
#import "VOLMessageCell.h"
#import "HTTPDefine.h"
#import "FMDatabase.h"
#import "VOLMessageCell.h"

#import "ASIHTTPRequest.h"
#import "ASIFormDataRequest.h"
#import "JSONKit.h"

#import <QuartzCore/QuartzCore.h>
@interface VOLmyMesgViewController (){
    
    VOLAppDelegate *del ;
    JSONDecoder *json ;
    
}
@end

@implementation VOLmyMesgViewController

- (id)initWithStyle:(UITableViewStyle)style
{
    self = [super initWithStyle:style];
    if (self) {
        // Custom initialization
    }
    return self;
}

- (void)viewDidLoad
{
    [super viewDidLoad];
    
    [super viewDidLoad];
    
    self.title = @"聊天记录";
    del = kGetDel ;
    addLeftNavigationBarButton() ;//添加返回主菜单按钮
    
    self.tableView.dataSource = self;
    self.tableView.delegate = self ;
    self.tableView.tableFooterView = [[UILabel alloc]init];
    
    
    //将用户数组按在线和名字排序
    NSSortDescriptor *sortonline = [NSSortDescriptor sortDescriptorWithKey:@"pearence" ascending:NO];
    NSSortDescriptor *sortname =  [NSSortDescriptor sortDescriptorWithKey:@"name" ascending:YES];
    
    NSArray *array = [del.rosters sortedArrayUsingDescriptors:@[sortonline,sortname]];
    NSMutableArray *myroster = [NSMutableArray arrayWithArray:array];
    del.rosters = myroster ;
    
    
    
    //消建立息中心，当用户的离线消息，状态等发生改变时，则更新消息
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(update:) name:@"ChangeNameNotice" object:nil];
    json = [[JSONDecoder alloc]init];
    
    
    //为导航栏添加编辑按钮
    UIBarButtonItem *deleteitem = [[UIBarButtonItem alloc]initWithTitle:@"编辑" style:UIBarButtonItemStylePlain target:self action:@selector(Edit:)];
    [deleteitem setTintColor:kThemeColor];
    [self.navigationItem setRightBarButtonItem:deleteitem];
    deleteitem.tag = 1 ;
    
    //加载各个用户的离线消息数量
    [self loadofflinemessage];
    
}

- (void)didReceiveMemoryWarning
{
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

#pragma mark - Table view data source

- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView
{
    
    return 1;
}

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
    
    return [del.rosters count];
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
    static NSString *CellIdentifier = @"messagecell";
    VOLMessageCell *cell = [tableView dequeueReusableCellWithIdentifier:CellIdentifier forIndexPath:indexPath];
    
    if (cell == nil) {
        
        cell = [[VOLMessageCell alloc]init];
        
    }
    
    
    //读取该用户的信息
    VOLChatUser *usr = [del.rosters objectAtIndex:indexPath.row];
    
    //    显示你与该用户的上一条聊天信息
    NSString *lastmessage = [self loadmessage:usr.name];
    if ((NSNull *)lastmessage == [NSNull null])
    {
        lastmessage = @"";
    }
    cell.messagelabel.text = lastmessage ;
    
    int offlinemessage = usr.offlinemessage ;
    
    UIImageView *imageview = [[UIImageView alloc]init] ;
    imageview.frame = CGRectMake(14, 8, 56, 56);
    imageview.layer.masksToBounds = YES ;
    imageview.layer.cornerRadius = 28 ;
    
    //若加载的headname为空，则直接加载本地图片
    if ((NSNull *)usr.headname == [NSNull null]) {
        imageview.image = [UIImage imageNamed:@"defaultHead.png"];
        
    }
    else{
        
        [self loadHeadImage:usr :imageview];
        
    }
    [cell.contentView addSubview:imageview];
    
    //若好友状态为在线
    if ([usr.pearence isEqualToString:@"available"])
    {
        cell.xmppNamelabel.textColor = [UIColor redColor];
        cell.xmppNamelabel.text = usr.volname ;
        cell.xmpppearencelabel.text = @"在线";
        
        if (offlinemessage > 0) {
            cell.offlinemsglabel.text = [NSString stringWithFormat:@"%d条未读消息",offlinemessage];
        }
        else {
            cell.offlinemsglabel.text = @"";
        }
        
    }
    
    //若好友住状态不为在线
    else
    {
        cell.xmppNamelabel.textColor = [UIColor grayColor];
        cell.xmppNamelabel.text = usr.volname ;
        cell.xmpppearencelabel.text = @"离线";
        
        if (offlinemessage > 0) {
            cell.offlinemsglabel.text = [NSString stringWithFormat:@"%d条未读消息",offlinemessage];
        }
        else {
            cell.offlinemsglabel.text = @"";
        }
    }
    
    
    return cell;
}


#pragma mark 菜单按钮的动作
- (void)showMenu:(id)sender {
    kActionOfMenuButton;
}


#pragma mark - viewwillapear时刷新数据
-(void)viewWillAppear:(BOOL)animated{
    [self.tableView reloadData];
}


#pragma mark-点击cell，跳转到聊天页面，并传入聊天对象的账户名
-(void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath{
    
    VOLChatViewController *chat = [[VOLChatViewController alloc]initWithNibName:@"VOLChatViewController" bundle:nil];
    VOLChatUser *user  = [del.rosters objectAtIndex:indexPath.row];
    chat.chatToName  = user.name ;
    
    [self.navigationController pushViewController:chat animated:YES];
    
}

#pragma amrk-收到消息中心，立即更新数据
-(void) update:(id)sender{
    
    [self.tableView reloadData];
    
}


#pragma mark - 设置cell的高度
-(CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath{
    
    return 70;
}





#pragma mark 加载头像图片
-(void)loadHeadImage:(VOLChatUser *)user :(UIImageView *)imageview {
    
    
    //创建文件夹
    NSFileManager *manager = [NSFileManager defaultManager];
    
    NSString *imageDocumentPath = [NSString stringWithFormat:@"%@%d/userHead/%d",kGetDocumentsPath,del.currentUser.userID,[user.userid intValue]];
    
    if (![manager fileExistsAtPath:imageDocumentPath])
    {
        
        [manager createDirectoryAtPath:imageDocumentPath withIntermediateDirectories:YES attributes:nil error:nil];
        
    }
    
    //先从本地查找是否已有图片
    NSString *imagePath = [NSString stringWithFormat:@"%@%d/userHead/%d/%@",kGetDocumentsPath,del.currentUser.userID,[user.userid intValue],user.headname];
    
    if ([manager fileExistsAtPath:imagePath]) {
        
        //        cell.headimage.image = [UIImage imageWithContentsOfFile:imagePath];
        imageview.image = [UIImage imageWithContentsOfFile:imagePath];
        
    }
    
    else{
        //若不存在，调用方法下载图片
        dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0), ^{
            
            //组装image的url
            NSString *urlstr = [NSString stringWithFormat:@"%@%d/%@",kUserHeadHome,[user.userid intValue],user.headname];
            NSURL *url = [NSURL URLWithString:urlstr];
            NSData *data = [NSData dataWithContentsOfURL:url];
            UIImage *image = [UIImage imageWithData:data];
            
            dispatch_async(dispatch_get_main_queue(), ^{
                if (image !=nil) {
                    //                    cell.headimage.image = image;
                    imageview.image =  [UIImage imageWithData:data];
                    if(  [data writeToFile:imagePath atomically:YES]){
                        NSLog(@"保存图片成功");
                        
                    }
                }
                else{
                    imageview.image = [UIImage imageNamed:@"defaultHead.png"];
                }
                
            });
        });
        
    }
    
    
    
    
    
    
}






#pragma mark - 点击编辑按钮，让tableview启动编辑
-(void)Edit:(UIBarButtonItem *)sender{
    if (sender.tag == 1) {
        self.tableView.editing = YES ;
        [sender setTitle:@"完成"];
        sender.tag = 2 ;
    }
    else{
        self.tableView.editing = NO ;
        [sender setTitle:@"编辑"];
        
        sender.tag = 1 ;
    }
    
}


#pragma mark - 启动编辑的代理方法
-(BOOL)tableView:(UITableView *)tableView canEditRowAtIndexPath:(NSIndexPath *)indexPath{
    
    return YES ;
    
}



#pragma mark - 处理删除动作
-(void)tableView:(UITableView *)tableView commitEditingStyle:(UITableViewCellEditingStyle)editingStyle forRowAtIndexPath:(NSIndexPath *)indexPath{
    
    if (editingStyle == UITableViewCellEditingStyleDelete) {
        
#pragma mark - 从服务器里消除这个好友
        VOLChatUser *chatuser = [del.rosters objectAtIndex:indexPath.row];
        NSString *name = chatuser.name ;
        XMPPJID *jid = [XMPPJID jidWithString:name];
        [del.xmpproster removeUser:jid];
        
        
        [del.rosters removeObjectAtIndex:[indexPath row]];
        
        
        [tableView deleteRowsAtIndexPaths:[NSArray arrayWithObject:indexPath] withRowAnimation:UITableViewRowAnimationLeft];
        
    }
    
}

#pragma mark-返回tableview编辑类型的代理方法
-(UITableViewCellEditingStyle)tableView:(UITableView *)tableView editingStyleForRowAtIndexPath:(NSIndexPath *)indexPath{
    
    return UITableViewCellEditingStyleDelete ;
}



#pragma mark - 通过电话号码获取用户名
-(NSString *) getusername:(NSString *)phonenumber {
    NSString *urlString = [NSString stringWithFormat:@"%@user/getHeadByUserPhone?userPhone=%@",kHTTPHome,phonenumber];
    NSURL *url = [NSURL URLWithString:urlString];
    ASIFormDataRequest *request = [ASIFormDataRequest requestWithURL:url];
    
    [request setRequestMethod:@"GET"];
    [request startSynchronous];
    NSData *data = [request responseData];
    NSString *username  = phonenumber ;
    if (data) {
        NSDictionary *dic = [json objectWithData:data];
        int status = [[dic objectForKey:@"status"] intValue];
        if (status == 1) {
            NSLog(@"success !!");
            
            NSArray *idhead = [dic objectForKey:@"idAndHead"];
            NSDictionary *k = [idhead objectAtIndex:0];
            username = [k objectForKey:@"user_name"];
            NSLog(@"------%@",k);
            
        }
        
    }
    return username ;
}

#pragma mark- 加载数据库里面保存的与该用户的聊天记录
-(NSString *) loadmessage:(NSString *)username{
    
    
    
    //读取数据库的内容
    FMDatabase *db = [FMDatabase databaseWithPath:[del getDBPath]];
    NSString *message ;
    if ([db open])
    {
        
        FMResultSet *rst =  [db executeQuery:@"select * from talk where messagefrom = ? or messageto = ?",username,username];
        while ([rst next])
        {
            
            message = [rst stringForColumnIndex:3]; //消息的内容
            
            
        }
    }
    NSLog(@"rrrr---%@",message);
    return message ;
    
}


#pragma mark - 加载plist文件保存的离线消息数量
-(void)loadofflinemessage{
    NSString *filename = [kGetDocumentsPath stringByAppendingPathComponent:@"offlinemessage.plist"];
    
    NSMutableDictionary *dic = [[NSMutableDictionary alloc]initWithContentsOfFile:filename];
    
    NSArray *usrarray = [dic allKeys];
    for (NSString *username in usrarray) {
        
        NSArray *uu = [dic objectForKey:username];
        
        for (VOLChatUser * chatuserd in del.rosters) {
            if ([chatuserd.name isEqualToString:username]) {
                NSNumber *number = [uu objectAtIndex:1];
                int h = [number intValue];
                chatuserd.offlinemessage = chatuserd.offlinemessage + h ;
            }
        }
        
    }
    
    
}

/*
 // Override to support conditional editing of the table view.
 - (BOOL)tableView:(UITableView *)tableView canEditRowAtIndexPath:(NSIndexPath *)indexPath
 {
 // Return NO if you do not want the specified item to be editable.
 return YES;
 }
 */

/*
 // Override to support editing the table view.
 - (void)tableView:(UITableView *)tableView commitEditingStyle:(UITableViewCellEditingStyle)editingStyle forRowAtIndexPath:(NSIndexPath *)indexPath
 {
 if (editingStyle == UITableViewCellEditingStyleDelete) {
 // Delete the row from the data source
 [tableView deleteRowsAtIndexPaths:@[indexPath] withRowAnimation:UITableViewRowAnimationFade];
 }
 else if (editingStyle == UITableViewCellEditingStyleInsert) {
 // Create a new instance of the appropriate class, insert it into the array, and add a new row to the table view
 }
 }
 */

/*
 // Override to support rearranging the table view.
 - (void)tableView:(UITableView *)tableView moveRowAtIndexPath:(NSIndexPath *)fromIndexPath toIndexPath:(NSIndexPath *)toIndexPath
 {
 }
 */

/*
 // Override to support conditional rearranging of the table view.
 - (BOOL)tableView:(UITableView *)tableView canMoveRowAtIndexPath:(NSIndexPath *)indexPath
 {
 // Return NO if you do not want the item to be re-orderable.
 return YES;
 }
 */

/*
 #pragma mark - Navigation
 
 // In a story board-based application, you will often want to do a little preparation before navigation
 - (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender
 {
 // Get the new view controller using [segue destinationViewController].
 // Pass the selected object to the new view controller.
 }
 
 */

@end
